﻿using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using WoodAdmin.Common.Helper;
using WoodAdmin.Models;
using System.Collections.Generic;
using WoodAdmin.Common.Attribute;
using SqlSugar;
using WoodAdmin.Models.ViewModels;
using SqlSugar.Extensions;

namespace WoodAdmin.Common.Filter
{
    /// <summary>
    /// 权限验证过滤器
    /// </summary>
    public class CheckPermissionFilters : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {

            //是否已登陆
            bool isSkipCheckLogin = context.ActionDescriptor.EndpointMetadata.Any(a => a.GetType() == typeof(SkipCheckLogin));

            //如果方法没有[SkipCheckLogin]且没有登录，则跳转到登陆页面
            var test = context.HttpContext.Session.GetString(APPKeys.CurrentUser);
            if(GlobalHelper.CurrentUser() == null && !isSkipCheckLogin ){
                context.Result = new ViewResult() { ViewName = "/Views/Login/Login.cshtml" };
            }

            var request = context.HttpContext.Request;

            //判断是否需要跳过校验
            bool isSkipCheckPermission = context.ActionDescriptor.EndpointMetadata.Any(a => a.GetType() == typeof(SkipCheckPermission));

            //如果不跳过权限校验
            if (!isSkipCheckPermission)
            { 
                //获取当前的URL
                string url = request.Path.Value.ToLower();
                string[] permissionName = url.Split('/');
                var action = "";
                if (permissionName.Length==2)
                {
                    action = "Index";
                }
                else
                {
                    action = permissionName[2];
                }
                var controller = permissionName[1];
                List<SysNode> userPermission = GlobalHelper.CurrentAuthNode();
                var ctrPermission = userPermission.FirstOrDefault(a => a.Name.ToLower().Equals(controller.ToLower()));

                if (ctrPermission == null)
                {
                    //判断是不是Ajax请求
                    if (request.IsAjaxRequest())
                    {
                        context.Result = new ContentResult
                        {
                            Content = JsonHelper.SerializeJSON(new FilterViewModel { status = 0, msg = "您没有操作权限", data = null }),
                            ContentType = "application/json;charset=UTF-8"
                        };
                    }
                    else
                    {
                        //2.跳转到 错误页面
                        context.Result = new ViewResult() { ViewName = "/Views/Home/PermissionError.cshtml" };
                    }
                }
                else
                {
                    var actPermission = userPermission.FirstOrDefault(a => a.Name.ToLower().Equals(action.ToLower()) && a.Pid.ObjToInt() == ctrPermission.ID);
                    if (actPermission == null)
                    {
                        //判断是不是Ajax请求
                        if (request.IsAjaxRequest())
                        {
                            context.Result = new ContentResult
                            {
                                Content = JsonHelper.SerializeJSON(new FilterViewModel { status=0,msg="您没有操作权限",data=null}),
                                ContentType = "application/json;charset=UTF-8"
                            };
                        }
                        else
                        {
                            //2.跳转到 错误页面
                            context.Result = new ViewResult() { ViewName = "/Views/Home/PermissionError.cshtml" };
                        }
                    }
                }
            }
        }
    }
}